#include "stdafx.h"
#include <pthread.h>
#include "ip_pack_queue.h"

#define MAX_IP_PACK			1536

struct list_entry
{
	struct list_entry*		next;
	struct list_entry*		prev;
};

struct http_get_pack
{
	struct list_entry		list;
	char					ippack[MAX_IP_PACK + 1];
};

struct ip_pack_queue
{
	struct list_entry		list;
	pthread_mutex_t			lock;
	long					count;
};


static struct ip_pack_queue	gip_pack_queue;

/*
 * 初始化队列
 */
void ip_pack_init()
{
	gip_pack_queue.list.next = &gip_pack_queue.list;
	gip_pack_queue.list.prev = &gip_pack_queue.list;
	gip_pack_queue.count = 0;
	pthread_mutex_init(&gip_pack_queue.lock, NULL);
}
/*
 * 添加到队列
 */
bool ip_pack_add(void *pdata, unsigned long len)
{
	struct http_get_pack*	pnew	= NULL;

	if(len > MAX_IP_PACK)
	{
		return false;
	}
	// 分配新空间
	pnew = (struct http_get_pack*)malloc(sizeof(struct http_get_pack));
	if(NULL == pnew)
	{
		return false; // 分配空间失败
	}
	// 复制数据
	memset(pnew, 0, sizeof(struct http_get_pack));
	memcpy(pnew->ippack, pdata, len);
	// 添加进队列
	pthread_mutex_lock(&gip_pack_queue.lock);
	gip_pack_queue.count++;
	pnew->list.next = gip_pack_queue.list.next;
	pnew->list.prev = &gip_pack_queue.list;
	gip_pack_queue.list.next->prev = &pnew->list;
	gip_pack_queue.list.next = &pnew->list;
	pthread_mutex_unlock(&gip_pack_queue.lock);

	return true;
}
/*
 * 获取队列数据
 */
bool ip_pack_get(void *pdata)
{
	struct http_get_pack*		pold	= NULL;
	
	if(0 >= gip_pack_queue.count)
	{
		return false;
	}

	// 将最后一个出队列
	pthread_mutex_lock(&gip_pack_queue.lock);
	gip_pack_queue.count--;
	pold = (struct http_get_pack *)gip_pack_queue.list.prev;
	gip_pack_queue.list.prev = gip_pack_queue.list.prev->prev;
	pold->list.prev->next = &gip_pack_queue.list;
	pthread_mutex_unlock(&gip_pack_queue.lock);
	// 复制数据
	memcpy(pdata, pold->ippack, MAX_IP_PACK);
	free(pold);

	return true;
}

